package com.td.erhome.ui.home;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.td.erhome.R;
import com.td.erhome.base.BaseFragment;
import com.td.erhome.models.BaseBean;
import com.td.erhome.models.VersinCodeBean;
import com.td.erhome.net.Api;
import com.td.erhome.net.BaseSubscriber;
import com.td.erhome.ui.agency.AgencyActivity;
import com.td.erhome.ui.bughouse.BugHouseListActivity;
import com.td.erhome.ui.historycost.CostAreaActivity;
import com.td.erhome.ui.login.LoginActivity;
import com.td.erhome.ui.min.MyMessageActivity;
import com.td.erhome.ui.sellhouse.FirstActivity;
import com.td.erhome.utils.UpdateInfoService;
import com.td.erhome.utils.UserManager;

import butterknife.Bind;
import butterknife.OnClick;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


public class HomeFragment extends BaseFragment {


    @Bind(R.id.re_bug_house)
    RelativeLayout mReBugHouse;
    @Bind(R.id.re_sell_house)
    RelativeLayout mReSellHouse;
    @Bind(R.id.re_serve)
    RelativeLayout mReServe;
    @Bind(R.id.re_cost)
    RelativeLayout mReCost;
    private Dialog mLoadingDialog;
    private ProgressDialog progressDialog;
    private UpdateInfoService mUpdateInfoService;
    private VersinCodeBean mData;

    public static HomeFragment newInstance() {
        Bundle bundle = new Bundle();
        HomeFragment homeFragment = new HomeFragment();
        homeFragment.setArguments(bundle);
        return homeFragment;
    }

    @Override
    protected void init() {
    }
    @Override
    public int getLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initView(View view) {
        getVersion();
    }

    @Override
    protected void initOperation() {

    }

    @OnClick({R.id.re_bug_house, R.id.re_sell_house, R.id.re_serve, R.id.re_cost})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.re_bug_house:
                Intent intent = new Intent(getActivity(), BugHouseListActivity.class);
                getActivity().startActivity(intent);
                break;
            case R.id.re_sell_house:
                if (UserManager.getIns().getUser()==null){
                    Intent intent1 = new Intent(getActivity(), LoginActivity.class);
                    getActivity().startActivity(intent1);
                    return;
                }if (!UserManager.getIns().getUser().is_profile_ok.equals("1")){
                     getActivity().startActivity(new Intent(getActivity(),MyMessageActivity.class));
                     return;
                }
                else {
                    Intent intent1 = new Intent(getActivity(), FirstActivity.class);
                    getActivity().startActivity(intent1);
                }

                break;
            case R.id.re_serve:
                Intent intent2 = new Intent(getActivity(), AgencyActivity.class);
                getActivity().startActivity(intent2);
                break;
            case R.id.re_cost:
                Intent intent3 = new Intent(getActivity(), CostAreaActivity.class);
                startActivity(intent3);
                break;
        }
    }

    //检查新版本
    public void getVersion() {

        PackageInfo packageInfo = null;
        try {
            PackageManager packageManager = getActivity().getApplication().getPackageManager();
            packageInfo = packageManager.getPackageInfo(getActivity().getApplication().getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        //当前版本号
        final String now_version = packageInfo.versionName;

        Api.getRetrofit().getAppVersion()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<BaseBean<VersinCodeBean>>(getActivity()){
                    @Override
                    public void onStart() {
                        super.onStart();
                    }
                    @Override
                    public void onNext(BaseBean<VersinCodeBean> upCodeBeanBaseBean) {
                        super.onNext(upCodeBeanBaseBean);
                        mData = upCodeBeanBaseBean.getData();
                        String code = mData.app_version;
                        if (Double.parseDouble(code)>Double.parseDouble(now_version)){
                            showUpdateDialog(mData.app_link,1);
                        }
                    //  showUpdateDialog(upCodeBeanBaseBean.getData().url, 0);
                    }
                });
    }



    //显示是否要更新的对话框
    public void showUpdateDialog(final String s, final int type) {

        LayoutInflater inflater = LayoutInflater.from(getActivity());
        View v = inflater.inflate(R.layout.updata_dialog_layout, null);

        TextView toastText = (TextView) v.findViewById(R.id.sure_tv);
        TextView card_num = (TextView) v.findViewById(R.id.cancel_bind_tv);

        toastText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                downFile(s,type);
                mLoadingDialog.dismiss();
            }
        });

        card_num.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mLoadingDialog.dismiss();
            }
        });
        // 创建自定义样式dialog
        mLoadingDialog = new Dialog(getActivity(), R.style.loading_dialog);

        mLoadingDialog.setCancelable(true);// 可以用"返回键"取消

        mLoadingDialog.setContentView(v, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));

        Window window = mLoadingDialog.getWindow();
        window.setGravity(Gravity.CENTER);  //此处可以设置dialog显示的位置

        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(lp);
        mLoadingDialog.show();
    }


    //下载
    public void downFile(String url, int type) {
        progressDialog = new ProgressDialog(getActivity());    //进度条，在下载的时候实时更新进度，提高用户友好度
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        if (type == 0) {
            progressDialog.setTitle("您的版本已不适用，正在更新");
        } else {
            progressDialog.setTitle("正在下载");
        }
        progressDialog.setMessage("请稍候...");
        progressDialog.setProgress(0);
        progressDialog.show();
        mUpdateInfoService = new UpdateInfoService(getActivity());
        mUpdateInfoService.downLoadFile(url, progressDialog);
    }

}
